/*
 *  This file is part of ZiggyStardust.
 *
 *  ZiggyStardust is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  ZiggyStardust is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.wisc.csvParser.plugins;

import com.wisc.csvParser.plugins.DataParserGleonServiceXML.events;
import javax.swing.JOptionPane;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author  lawinslow
 */
public class JPanelGleonXML extends javax.swing.JPanel {
    DataParserGleonServiceXML parser;
    int currSource;

    /** Creates new form JPanelGleonXML
     * @param parser Underlying parser object
     */
    public JPanelGleonXML(DataParserGleonServiceXML parser) {
        initComponents();
        
        this.parser = parser;
        updatePanel();
        
        parser.addEventHandler(new DataParserGleonServiceXML.IEventHandler() {

            @Override
            public void eventRaised(events e) {
                handleEvent(e);
            }
        });
    }
    
    private void handleEvent(DataParserGleonServiceXML.events e){
        if(e==DataParserGleonServiceXML.events.started){
            updatePanel();
        }else if(e==DataParserGleonServiceXML.events.stopped){
            updatePanel();
        }else if(e==DataParserGleonServiceXML.events.updated){
            updatePanel();
        }else if(e==DataParserGleonServiceXML.events.valsParsed){
            updatePanel();
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        sourceList = new javax.swing.JList();
        addButton = new javax.swing.JButton();
        getCustomButton = new javax.swing.JButton();
        removeButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        urlField = new javax.swing.JTextField();
        saveChangesButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lcaField = new javax.swing.JTextField();
        ldpdField = new javax.swing.JTextField();
        ncaField = new javax.swing.JTextField();
        nvcField = new javax.swing.JTextField();

        sourceList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                sourceListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(sourceList);

        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        getCustomButton.setText("Get Custom");
        getCustomButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getCustomButtonActionPerformed(evt);
            }
        });

        removeButton.setText("Remove");
        removeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Source:");

        jLabel2.setText("URL:");

        nameField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameFieldActionPerformed(evt);
            }
        });

        saveChangesButton.setText("Save Changes");
        saveChangesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveChangesButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nameField, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(saveChangesButton))
                            .addComponent(urlField, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(urlField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(saveChangesButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel3.setText("Last Attempt:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel4.setText("Last Data Point:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel5.setText("Next Attempt:");

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel6.setText("Number of Values:");

        lcaField.setEditable(false);
        lcaField.setFont(new java.awt.Font("Tahoma", 0, 10));
        lcaField.setBorder(null);

        ldpdField.setEditable(false);
        ldpdField.setFont(new java.awt.Font("Tahoma", 0, 10));
        ldpdField.setBorder(null);

        ncaField.setEditable(false);
        ncaField.setFont(new java.awt.Font("Tahoma", 0, 10));
        ncaField.setBorder(null);

        nvcField.setEditable(false);
        nvcField.setFont(new java.awt.Font("Tahoma", 0, 10));
        nvcField.setBorder(null);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lcaField, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ldpdField, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ncaField, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nvcField, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lcaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(ldpdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(ncaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(nvcField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(getCustomButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addButton)
                    .addComponent(removeButton)
                    .addComponent(getCustomButton))
                .addContainerGap(27, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        String name = JOptionPane.showInputDialog("Please enter source name.");
        if(name == null || name.compareTo("")==0){
            return;
        }
        
        String url = JOptionPane.showInputDialog("Please enter source URL.");
        if(url == null || url.compareTo("")==0){
            return;
        }
        parser.addSource(name, url);
        currSource = parser.getSources().size() - 1;
    }//GEN-LAST:event_addButtonActionPerformed

    private void getCustomButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getCustomButtonActionPerformed
        if(sourceList.getSelectedValue() != null){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String temp = null;
            try{
                //get starting retrieval interval date
                temp = JOptionPane.showInputDialog("Start Date (yyyy-MM-dd)");
                if(temp==null){//user hit cancel
                    return;
                }
                Date start = format.parse(temp);
                //get latest date to attempt retrieval
                temp = JOptionPane.showInputDialog("End Date (yyyy-MM-dd)");
                if(temp==null){//user hit cancel
                    return;
                }
                Date end = format.parse(temp);
                DataParserGleonServiceXML.XmlSource test =
                        ((DataParserGleonServiceXML.XmlSource)
                        sourceList.getSelectedValue());
                ((DataParserGleonServiceXML.XmlSource)
                        sourceList.getSelectedValue()).tryRetrievalCustomAsync(start, end);
                JOptionPane.showMessageDialog(null, "Download Scheduled.");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_getCustomButtonActionPerformed

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
        if (sourceList.getSelectedValue() != null) {
            parser.removeSource((DataParserGleonServiceXML.XmlSource)sourceList.getSelectedValue());
        }
    }//GEN-LAST:event_removeButtonActionPerformed

    private void nameFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameFieldActionPerformed
        // TODO add youhandling code here:
    }//GEN-LAST:event_nameFieldActionPerformed

    private void saveChangesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveChangesButtonActionPerformed
        if (sourceList.getSelectedValue() != null) {
            DataParserGleonServiceXML.XmlSource x = (DataParserGleonServiceXML.XmlSource)sourceList.getSelectedValue();
            x.changeName(nameField.getText());
            x.changeURL(urlField.getText());
        }
        updatePanel();
    }//GEN-LAST:event_saveChangesButtonActionPerformed

    private void sourceListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_sourceListValueChanged

        try{
            if(sourceList.getSelectedValue() != null){
                DataParserGleonServiceXML.XmlSource x = (DataParserGleonServiceXML.XmlSource)sourceList.getSelectedValue();
                nameField.setText(x.getName());
                urlField.setText(x.getURL());
                currSource = parser.getSources().indexOf(x);
            }
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }//GEN-LAST:event_sourceListValueChanged

    private void updatePanel() {
        SimpleDateFormat format =
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sourceList.setListData(parser.getSources().toArray(new DataParserGleonServiceXML.XmlSource[1]));
        if (sourceList.getSelectedValue() != null) {
            DataParserGleonServiceXML.XmlSource x = (DataParserGleonServiceXML.XmlSource) sourceList.getSelectedValue();
            nameField.setText(x.getName());
            urlField.setText(x.getURL());
            lcaField.setText(x.getLastCollectionAttempt().toString());
            ldpdField.setText(x.getLastDataPointDownloaded().toString());
            ncaField.setText(x.getNextCollectionAttempt().toString());
            nvcField.setText(x.getNumValuesCollected().toString());
        } else if (parser.getSources().size() == 1) {
            try {
                nameField.setText(parser.getSources().get(0).getName());
                urlField.setText(parser.getSources().get(0).getURL());
                lcaField.setText(format.format(parser.getSources().get(0).getLastCollectionAttempt()));
                ldpdField.setText(format.format(parser.getSources().get(0).getLastDataPointDownloaded()));
                ncaField.setText(format.format(parser.getSources().get(0).getNextCollectionAttempt()));
                nvcField.setText(parser.getSources().get(0).getNumValuesCollected().toString());
            } catch (NullPointerException e) {
            }
        } else {
            try {
                lcaField.setText(format.format(parser.getSources().get(currSource).getLastCollectionAttempt()));
                ldpdField.setText(format.format(parser.getSources().get(currSource).getLastDataPointDownloaded()));
                ncaField.setText(format.format(parser.getSources().get(currSource).getNextCollectionAttempt()));
                nvcField.setText(parser.getSources().get(currSource).getNumValuesCollected().toString());
            } catch (Exception e) {
            }
        }
    }

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton getCustomButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField lcaField;
    private javax.swing.JTextField ldpdField;
    private javax.swing.JTextField nameField;
    private javax.swing.JTextField ncaField;
    private javax.swing.JTextField nvcField;
    private javax.swing.JButton removeButton;
    private javax.swing.JButton saveChangesButton;
    private javax.swing.JList sourceList;
    private javax.swing.JTextField urlField;
    // End of variables declaration//GEN-END:variables
    
}
